#include <sys/types.h>
#include <sys/param.h>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <cstdarg>
#include <cstdio>

#include "CommunicationModule/Request.h"
#include "CommunicationModule/Response.h"
#include "CommunicationModule/Info.h"


int _DLM_send(const Request &request, int size)
{
	char response = DLM_FAILED;	
	assert(size <= PIPE_BUF);
	write(STDOUT_FILENO, &request, size);
	read(STDIN_FILENO, &response, 1);
	
	return response;
}



int DLM_lock(int resource_id, int lock_type, long timeout)
{
	LockRequest request(getpid(), resource_id, (LockType)lock_type, timeout);

	return _DLM_send(request, sizeof(request));
}



int DLM_unlock(int resource_id)
{
	UnlockRequest request(getpid(), resource_id);
	
	return _DLM_send(request, sizeof(request));
}



int DLM_trylock(int resource_id, int lock_type)
{
	TryLockRequest request(getpid(), resource_id, (LockType)lock_type);

	return _DLM_send(request, sizeof(request));
}



int DLM_info(const char *format, ...)
{
	va_list args;
	va_start(args, format);
	
	char buffer[PIPE_BUF] = { 0 };
	
	struct InfoHeader *ih = (struct InfoHeader *)buffer;
	
	char *msg = (char *)(ih+1);
	
	ih->pid = getpid();	
	ih->msgLen = vsnprintf(msg, PIPE_BUF - sizeof(struct InfoHeader), format, args);	
		
	write(STDERR_FILENO, buffer, sizeof(struct InfoHeader) + ih->msgLen);
	
	return ih->msgLen;
}




